package org.maxgroundstation.groundstation.comm.service;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * A class that handles sending service TCP communication.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ServiceSenderTCP {
    
    // Data members
    private ServiceCommunicationTCP comm;
    private DataOutputStream out;
	
    /**
     * Constructor
     * @param comm the service communication TCP.
     */
    ServiceSenderTCP(ServiceCommunicationTCP comm) {
    	this.comm = comm;
    	out = null;
    }
    
    /**
     * Initializes the output data stream from the socket.
     * @throws IOException if error initializing the output stream.
     */
    void initializeOutputDataStream() throws IOException {
    	out = new DataOutputStream(new BufferedOutputStream(comm.getSocket().getOutputStream()));
    }
    
    /**
     * Closes the output data stream.
     * @throws IOException if error closing the output stream.
     */
    void closeOutputDataStream() throws IOException {
    	try {
    		if (out != null) out.close();
    		out = null;
    	}
    	catch (IOException e) {
    		System.err.println("Error closing TCP sender stream: " + e.getMessage());
    	}
    }
    
    /**
     * Sending a service post.
     * @param serviceID the service ID.
     * @param data the post data.
     */
    void sendServicePost(String serviceID, byte[] data) {
    	String clientID = comm.getServiceCommunication().getClientID();
    	ServiceDataFragment dataFrag = ServiceUtil.createDataFragment(serviceID, 
    			clientID, (long) data.length, 0, data);
    	
    	if (comm.isConnected()) {
    		//System.out.println("Sending TCP Service Post");
            try {
            	byte[] packetData = dataFrag.toPacketData();
            	out.write(packetData);
            	out.flush();
            }
            catch (IOException e) {
                System.err.println("Error sending service TCP data: " + e.getMessage());
            }
        }
    }
}